
Partial Class Case_StatusHistory
    Inherits System.Web.UI.Page

    Dim allStatusList As Hashtable
    Dim allStatusReasonList As Hashtable

    Public Function GetStatusDescription(ByVal caseStatusId As Integer) As String
        If allStatusList Is Nothing Then
            allStatusList = New Hashtable()
            Dim statusObjectList As System.Collections.Generic.List(Of Cdm.DataCore.LookupTables.LuCaseStatus)
            statusObjectList = StatusList()
            For i As Integer = 0 To statusObjectList.Count - 1
                allStatusList.Add(statusObjectList(i).CaseStatusId, statusObjectList(i).Description)
            Next
        End If

        If allStatusList.ContainsKey(caseStatusId) Then
            Return allStatusList.Item(caseStatusId).ToString()
        Else
            Return ""
        End If

    End Function

    Public Function GetStatusReasonDescription(ByVal caseStatusReasonId As Integer) As String
        If allStatusReasonList Is Nothing Then
            allStatusReasonList = New Hashtable()
            Dim statusReasonObjectList As System.Collections.Generic.List(Of Cdm.DataCore.CaseNotes.CaseStatusReason)
            statusReasonObjectList = Cdm.DataCore.CaseNotes.CaseStatusReason.ListAll()
            For i As Integer = 0 To statusReasonObjectList.Count - 1
                allStatusReasonList.Add(statusReasonObjectList(i).CaseStatusReasonId, statusReasonObjectList(i).Description)
            Next
        End If

        If allStatusReasonList.ContainsKey(caseStatusReasonId) Then
            Return allStatusReasonList.Item(caseStatusReasonId).ToString()
        Else
            Return ""
        End If

    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ValidationErrorSummary1.Visible = False
        If Not Me.IsPostBack Then
            BindGrid()
            TitleLabel.Text = "File Status History for " & EntityController.GetParticipant().DisplayLastNameFirst
        End If
        WriteStatusHistoryJavaScript()
    End Sub

    Private Sub BindGrid()
        Dim participantId As Integer = EntityController.GetParticipant().ParticipantId
        Me.StatusHistoryGridView.DataSource = Cdm.DataCore.Entities.ParticipantStatusHistory.ListByParticipant(participantId)
        StatusHistoryGridView.DataBind()
        Dim lastColumn As Integer = StatusHistoryGridView.Columns.Count - 1
        StatusHistoryGridView.Columns(lastColumn).Visible = UserHasEditPermission()

    End Sub

    Private Sub WriteStatusHistoryJavaScript()
        Dim sbJava As New StringBuilder("<script language=""javascript"">")
        sbJava.Append(vbLf)
        sbJava.Append("function addAllOptions(objReasonDDL,selectedStatus)")
        sbJava.Append(vbLf)
        sbJava.Append("{")
        sbJava.Append(vbLf)

        Dim reasons As System.Collections.Generic.List(Of Cdm.DataCore.CaseNotes.CaseStatusReason) = Cdm.DataCore.CaseNotes.CaseStatusReason.ListAll()
        For i As Integer = 0 To reasons.Count - 1
            If reasons(i).CaseStatusId > 0 Then
                sbJava.Append(String.Format("if (selectedStatus=='{0}') ", reasons(i).CaseStatusId.ToString()))
            End If
            Dim line As String = String.Format("addOption(objReasonDDL,'{0}','{1}');", _
                                reasons(i).Description, reasons(i).CaseStatusReasonId.ToString())
            sbJava.Append(line)
            sbJava.Append(vbLf)
        Next
        sbJava.Append(vbLf)
        sbJava.Append("}")
        sbJava.Append("</script>")
        'Response.Write(sbJava.ToString())
        'ClientScript.RegisterClientScriptBlock
        Me.RegisterClientScriptBlock("aaa", sbJava.ToString())
    End Sub

    Protected Sub StatusHistoryGridView_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles StatusHistoryGridView.PageIndexChanging
        StatusHistoryGridView.PageIndex = e.NewPageIndex
        BindGrid()
    End Sub

    Protected Sub StatusHistoryGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles StatusHistoryGridView.RowCancelingEdit
        StatusHistoryGridView.EditIndex = -1
        BindGrid()
    End Sub

    Protected Sub StatusHistoryGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles StatusHistoryGridView.RowDataBound
        Dim statusDropDown As DropDownList = CType(e.Row.FindControl("EditStatusDropDownList"), DropDownList)
        Dim statusReasonDropDown As DropDownList = CType(e.Row.FindControl("EditStatusReasonDropDownList"), DropDownList)
        If Not statusDropDown Is Nothing Then
            statusDropDown.DataSource = StatusList()
            statusDropDown.DataBind()
            statusDropDown.SelectedValue = CStr(StatusHistoryGridView.DataKeys(e.Row.RowIndex).Item(1))
            statusDropDown.Enabled = UserHasEditPermission()
        End If

        If Not statusReasonDropDown Is Nothing Then
            statusReasonDropDown.DataSource = StatusReasonList(StatusHistoryGridView.DataKeys(e.Row.RowIndex).Item(1))
            statusReasonDropDown.DataBind()
            statusReasonDropDown.SelectedValue = CStr(StatusHistoryGridView.DataKeys(e.Row.RowIndex).Item(2))
            statusReasonDropDown.Enabled = UserHasEditPermission()
            statusDropDown.Attributes.Add("onChange", String.Format("resetStatusList('{0}','{1}');", statusDropDown.UniqueID, statusReasonDropDown.UniqueID))
        End If


    End Sub

    Private Function StatusList() As System.Collections.Generic.List(Of Cdm.DataCore.LookupTables.LuCaseStatus)
        Return Cdm.DataCore.LookupTables.LuCaseStatus.ListAll()
    End Function

    Private Function StatusReasonList(ByVal caseStatusId As Integer) As System.Collections.Generic.List(Of Cdm.DataCore.CaseNotes.CaseStatusReason)
        Return Cdm.DataCore.CaseNotes.CaseStatusReason.ListByCaseStatus(caseStatusid)

    End Function
    ''' <summary>
    ''' Checks if user has
    '''    1) Permission to update file personal info, and
    '''    2) Permission to update the case status field
    ''' If either of these is no, then current user does not have permission
    ''' to edit file status, and this page is read only.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function UserHasEditPermission() As Boolean
        'Check if user has permission to update file personal info
        If Not UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CasePersonal) Then
            Return False
        End If

        'Check if user has permission to update File Status (field CaseStatusId)
        If Not UserAuthorization.CurrentUser.HasFormLevelPermission("Participant", "CaseStatusId") Then
            Return False
        End If

        'If both of the above pass, then user has permission to update.
        Return True
    End Function

    Protected Sub StatusHistoryGridView_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles StatusHistoryGridView.RowEditing
        StatusHistoryGridView.EditIndex = e.NewEditIndex
        BindGrid()
    End Sub

    Protected Sub StatusHistoryGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles StatusHistoryGridView.RowUpdating
        Dim errorList As New ArrayList
        Dim estReturnTextBox As TextBox = StatusHistoryGridView.Rows(e.RowIndex).FindControl("EditEstimatedReturnDateTextBox")
        Dim commentsTextBox As TextBox = StatusHistoryGridView.Rows(e.RowIndex).FindControl("EditCommentsTextBox")
        Dim effectiveDateTextBox As TextBox = StatusHistoryGridView.Rows(e.RowIndex).FindControl("EditEffectiveDateTextBox")

        Dim statusDropdownList As DropDownList = StatusHistoryGridView.Rows(e.RowIndex).FindControl("EditStatusDropDownList")
        Dim statusReasonDropdownList As DropDownList = StatusHistoryGridView.Rows(e.RowIndex).FindControl("EditStatusReasonDropDownList")

        Dim statusHistoryId = CInt(StatusHistoryGridView.DataKeys(e.RowIndex).Item(0))
        Dim updateStatusHistory As Cdm.DataCore.Entities.ParticipantStatusHistory = Cdm.DataCore.Entities.ParticipantStatusHistory.Retrieve(statusHistoryId)
        updateStatusHistory.CaseStatusId = CInt(statusDropdownList.SelectedValue)
        updateStatusHistory.CaseStatusReasonId = CInt(statusReasonDropdownList.SelectedValue)
        updateStatusHistory.Comments = commentsTextBox.Text

        If IsDate(estReturnTextBox.Text) Then
            updateStatusHistory.EstimatedReturnDate = CDate(estReturnTextBox.Text)
        Else
            If estReturnTextBox.Text <> "" Then
                errorList.Add("Please Enter a valid date for Estimated return date.")
            End If
        End If

        If IsDate(effectiveDateTextBox.text) Then
            updateStatusHistory.EffectiveDate = CDate(effectiveDateTextBox.text)
        Else
            errorList.Add("Please Enter a valid date for Effective Date")
        End If
        If errorList.Count > 0 Then
            ValidationErrorSummary1.SetErrors(errorList)
            ValidationErrorSummary1.Visible = True
            e.Cancel = True
        Else
            updateStatusHistory.DateModified = DateTime.Now
            updateStatusHistory.Persist()
        End If
        
    End Sub
End Class
